package com.live.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.live.model.Admin;
import com.live.service.AdminService;
import com.live.util.DesTool;
import com.live.util.StringUtil;

@WebServlet("/adminAdd")
public class AdminAddController extends HttpServlet implements Servlet {
	private final Logger logger = Logger.getLogger(AdminAddController.class);
	private static final long serialVersionUID = 1L;
	private AdminService adminService;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			HttpSession session = request.getSession(true);
			Admin admin = (Admin) session.getAttribute("CurrentUser");
			if (admin != null) {
				RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/view/adminAdd.jsp");  
				rd.forward(request, response);  
				 return;  
			}
			RequestDispatcher rd = request.getRequestDispatcher("login.jsp");  
			rd.forward(request, response);  
			 return;  
		} catch (Exception e) {
			e.printStackTrace();
			RequestDispatcher rd = request.getRequestDispatcher("login.jsp");  
			rd.forward(request, response);  
	         return;  
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("执行添加员工doPost方法");
		String name = request.getParameter("name").trim();
		String account = request.getParameter("account").trim();
		String password = request.getParameter("password").trim();
		String mail = request.getParameter("mail").trim();
		String comments = request.getParameter("comments").trim();
		try {
			name = new String(name.getBytes("ISO-8859-1"),"UTF-8");
			comments = new String(comments.getBytes("ISO-8859-1"),"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("------addAdmin  addAdmin = " + e.getMessage());
		}
		adminService =new AdminService();
		Admin  admin = new Admin();
		if(password == null||password.equals("")){
			admin.setPassword(DesTool.encode("P@ssword123"));
		}else {
			System.err.println(password);
			admin.setPassword(DesTool.encode(password));
		}
		admin.setAccount(account);
		admin.setComments(comments);
		admin.setName(name);
		admin.setMail(mail);
		admin.setTime(StringUtil.getStrDateTime());
		admin.setRole(2);
		admin.setSign(0);
		admin.setSpecial(0);
		adminService.addAdmin(admin);
		logger.debug("------addAdmin  addAdmin = " + admin);
		response.sendRedirect(request.getContextPath() + "/adminList");// 跳转
	}

}
